home *** CD-ROM | disk | FTP | other *** search
/ BBS in a Box 15 / BBS in a box XV-1.iso / Files / Educ / Calc / MathPad 2.35.sit / XFuns / XFun kit / linfit.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-04-29  |  1.4 KB  |  63 lines  |  [TEXT/KAHL]

  1. /* linfit(XYpoints)
  2.  Fit data to a straight line using linear regression formula.
  3. */
  4.  
  5. #include "callback.h"
  6. #include <SANE.h>        // needed for sqrt()
  7.  
  8. BOOL linfit(extended *retval,funptr callback)
  9. {
  10.    EXPR arr;
  11.    extended x,y,*iptr,*jptr,intercept;
  12.    extended sumx,sumxx,sumy,sumyy,sumxy,Sxx,Sxy;
  13.    BOOL isarray;
  14.    long n,count;
  15.    
  16.    sumx=0; sumxx=0; sumy=0; sumyy=0; sumxy=0;
  17.    n = 0;
  18.    MakeParmExpr(0,&arr,callback);
  19.    ProbeExpr(arr,&x,&isarray,&count,callback);
  20.    if(!isarray || count<2)
  21.    {
  22.     ErrMsg(" linfit() expects array of {x,y}",0L,callback);
  23.     FreeExpr(arr,callback);
  24.     return(FALSE);
  25.    }
  26.    AddIndex(&arr,&iptr,callback);    // arr[i] is {x,y}
  27.    AddIndex(&arr,&jptr,callback);    // j picks x or y
  28.    while(count--)
  29.    {
  30.     *jptr = 1;
  31.     if(EvalExpr(arr,&x,callback) && x==x)
  32.     {
  33.      *jptr = 2;
  34.      if(EvalExpr(arr,&y,callback) && y==y)
  35.      {
  36.       sumx += x;
  37.       sumxx += x*x;
  38.       sumy += y;
  39.       sumyy += y*y;
  40.       sumxy += x*y;
  41.       n++;
  42.      }
  43.     }
  44.     *iptr += 1;
  45.    }
  46.    Sxx=n*sumxx-sumx*sumx;
  47.    Sxy=n*sumxy-sumx*sumy;
  48.  
  49.    SetVarVal("slope",Sxy/Sxx,callback);
  50.    intercept=(sumxx*sumy-sumx*sumxy)/(n*sumxx-sumx*sumx);
  51.    SetVarVal("intercept",intercept,callback);
  52.    *retval = Sxy/sqrt(Sxx*(n*sumyy-sumy*sumy));        // return correlation coeff
  53.    
  54.    FreeExpr(arr,callback);
  55.    return(TRUE);
  56. }
  57.  
  58. void main(funptr callback)
  59. {
  60.    AddXfun("linfit","XYpoints",&linfit,NULL,callback);
  61. }
  62.  
  63.